package com.telit.common.handler;

import com.telit.common.util.AesUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * AES加解密类型处理器
 * Create by Chencf 2023/02/08
 */
public class AESEncryptHandler extends BaseTypeHandler<String> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (Objects.isNull(parameter)) {
            ps.setString(i, null);
        } else {
            ps.setString(i, AesUtil.encrypt(parameter));
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        if (Objects.isNull(result)) {
            return null;
        }
        return AesUtil.decrypt(result);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        if (Objects.isNull(result)) {
            return null;
        }
        return AesUtil.decrypt(result);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        if (Objects.isNull(result)) {
            return null;
        }
        return AesUtil.decrypt(result);
    }
}
